package com.heima.datasync.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVo;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class EsDataServiceImpl implements EsDataService {

    public static final String ARTICLE_INDEX_NAME = "app_info_article";

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public ResponseResult dataInit() {
        try {
            //查询第一页文章数据
            List<ApArticle> apArticleList = apArticleMapper.findAllArticles();
            if (apArticleList == null || apArticleList.size() == 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "数据库文章数据不存在");
            }
            //对es索引库进行批量插入
            BulkRequest bulkRequest = new BulkRequest(ARTICLE_INDEX_NAME);
            for (ApArticle apArticle : apArticleList) {
                SearchArticleVo articleVo = new SearchArticleVo();
                BeanUtils.copyProperties(apArticle, articleVo);

                String articleJson = JSON.toJSONString(articleVo);

                IndexRequest indexRequest = new IndexRequest();
                indexRequest.id(apArticle.getId().toString())
                        .source(articleJson, XContentType.JSON);

                bulkRequest.add(indexRequest);
            }
            BulkResponse response = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

            return ResponseResult.okResult(response.status());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }
}